#include "Stack.h"

void StackInit(ST *st)
{
    st->p = NULL;
    st->top = 0;
    st->Capacity = 0;
}

void StackDestory(ST *st)
{
    assert(st);
    free(st->p);
    st->p = NULL;
    st->top = 0;
    st->Capacity = 0;
}

void StackPush(ST *st, STDataType x)
{
    assert(st);
    //扩容
    if (st->Capacity == st->top)
    {
        int newCapacity = st->Capacity == 0 ? 2 : st->Capacity * 2;
        st->p = (STDataType *)realloc(st->p, sizeof(STDataType) * newCapacity);
        if (st->p == NULL)
        {
            printf("realloc fail!!!\n");
            exit(EXIT_FAILURE);
        }
        st->Capacity = newCapacity;
    }
    //在栈顶插入数据
    st->p[st->top] = x;
    ++st->top;
}

void StackPop(ST *st)
{
    assert(st);
    //当栈没有变量时，继续出栈会导致越界
    assert(st->top > 0);
    --st->top;
}

bool StackEmpty(ST *st)
{
    assert(st);
    //如果top为0则返回true，反之false
    return st->top == 0;
}

int StackSize(ST *st)
{
    assert(st);
    return st->top;
}

STDataType StackTop(ST *st)
{
    assert(st);
    return st->p[st->top - 1];
}

int main()
{
    ST s;
    //初始化栈
    StackInit(&s);
    //压栈
    StackPush(&s, 1);
    StackPush(&s, 2);
    //出栈
    StackPop(&s);
    StackPush(&s, 3);
    StackPush(&s, 4);
    StackPush(&s, 5);
    StackPush(&s, 6);

    //出栈
    StackPop(&s);
    StackPop(&s);

    while (!StackEmpty(&s)) //判断栈是否为空
    {
        printf("%d ", StackTop(&s)); //打印栈顶的数据
        StackPop(&s);                //出栈
    }
    printf("\n");
    //释放栈
    StackDestory(&s);

    system("pause");
    return 0;
}